package com.yq.design.proxy.dynamicProxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName CglibFactory
 * @Description TODO
 * @Author yaoqiang
 * @Date 2021/3/1 11:58
 * @Version 1.0
 */
public class CglibFactory implements MethodInterceptor {
    private Object target;

    public CglibFactory(Object target) {
        this.target = target;
    }

    //返回一个代理对象，是target对象的代理对象
    public Object getProxyInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
//重写intercept方法，会调用目标对象的方法
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib start");
        Object invoke = method.invoke(target);
        System.out.println("cglib end");
        return invoke;
    }
}
